<template>
  <div class="container">
    <el-dialog
      :title="dialog.dialogType === 'edit' ? '修改改账单' : '创建改账单'"
      :visible.sync="dialog.dialogVisible"
      width="500px"
      fullscreen
      center
      :lock-scroll="true"
      @close="hideDialog"
      @open="getData"
    >
      <div class="main">
        <div class="left">
          <div class="title">原账单</div>
          <div class="search">
            <p class="searchName">结算单号：</p>
            <el-input
            clearable
              class="searchInp"
              v-model="searchCode"
              placeholder="请输入结算单号"
            />
            <el-button type="primary" icon="el-icon-search" @click="search()"
              >查询</el-button
            >
          </div>
          <el-form
            ref="form"
            :rules="rules"
            :model="formData1"
            label-width="100px"
            label-position="left"
          >
            <el-form-item label="供应商编码：">
              <p class="inps">
                {{ formData1.supplier ? formData1.supplier.code : "" }}
              </p>
            </el-form-item>
            <el-form-item label="供应商名称：">
              <p class="inps">
                {{ formData1.supplier ? formData1.supplier.name : "" }}
              </p>
            </el-form-item>
            <el-form-item label="配送中心编码：">
              <p class="inps">
                {{ formData1.rdc_code }}
              </p>
            </el-form-item>
            <el-form-item label="配送中心名称：">
              <p class="inps">
                {{ formData1.rdc_name }}
              </p>
            </el-form-item>
            <el-form-item label="采购员编码：">
              <p class="inps">
                {{ formData1.buyer_code }}
              </p>
            </el-form-item>
            <el-form-item label="采购员名称：">
              <p class="inps">
                {{ formData1.buyer }}
              </p>
            </el-form-item>
            <el-form-item label="金额：">
              <p class="inps">
                {{ formData1.amount }}
              </p>
            </el-form-item>
            <el-form-item label="数量：">
              <p class="inps">
                {{ formData1.goods_num }}
              </p>
            </el-form-item>
            <el-form-item label="单价：">
              <p class="inps">
                {{ formData1.goods_price }}
              </p>
            </el-form-item>
          </el-form>
        </div>
        <div class="right">
          <div class="title">改账单</div>
          <div class="search"></div>
          <el-form
            ref="form"
            :rules="rules"
            :model="formData"
            label-width="100px"
            label-position="left"
          >
            <el-form-item label="改账金额：">
              <el-input-number
                :precision="4"
                :controls="false"
                v-model="formData.amount"
                @change="onPrice"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="改账数量：">
              <el-input-number
                :precision="4"
                :controls="false"
                v-model="formData.num"
                @change="onPrice"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="改账单价：">
              <el-input-number
                :disabled="true"
                :precision="4"
                :controls="false"
                v-model="formData.price"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="改账件数：">
              <el-input-number
                :precision="4"
                :controls="false"
                v-model="formData.qty"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="改账供应商：">
              <el-select
                v-model="supplierData.value"
                :multiple="false"
                filterable
                remote
                center
                reserve-keyword
                placeholder="请选择供应商"
                :remote-method="supplierMethod"
                :loading="supplierData.loading"
                @change="supplierOn(supplierData.value)"
              >
                <el-option
                  v-for="item in supplierData.list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="institution">
            <div class="search">
              <p class="searchName">改账机构：</p>
              <el-select
                v-model="institutionData.value"
                :multiple="false"
                filterable
                remote
                center
                reserve-keyword
                placeholder="请选择改账机构"
                :remote-method="institutionMethod"
                :loading="institutionData.loading"
              >
                <el-option
                  v-for="item in institutionData.list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-button
                style="margin-left: 10px;"
                icon="el-icon-circle-plus"
                type="primary"
                @click="addInstitution"
                >添加改账机构</el-button
              >
              <el-button
                type="primary"
                class="handleSearch"
                icon="el-icon-upload"
                @click="download()"
                >模板下载</el-button
              >

              <el-upload
                class="upload-demo"
                style="display: inline; margin-left: 10px"
                action="#"
                :show-file-list="false"
                :http-request="handleAvatarSuccess"
              >
                <el-button
                  type="primary"
                  class="handleSearch"
                  icon="el-icon-circle-plus"
                  >导入机构</el-button
                >
              </el-upload>
            </div>
            <el-table :data="institutionList" border style="width: 1000px">
              <el-table-column align="center" prop="org_name" label="机构名称">
              </el-table-column>
              <el-table-column
                align="center"
                prop="org_amount"
                label="调整金额"
              >
                <template slot-scope="scope">
                  <el-input-number
                    size="mini"
                    :precision="4"
                    :controls="false"
                    v-model="scope.row.org_amount"
                    @change="onPrice"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="org_num" label="调整数量">
                <template slot-scope="scope">
                  <el-input-number
                    size="mini"
                    :precision="4"
                    :controls="false"
                    v-model="scope.row.org_num"
                    @change="onPrice"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="org_qty" label="调整件数">
                <template slot-scope="scope">
                  <el-input-number
                    size="mini"
                    :precision="4"
                    :controls="false"
                    v-model="scope.row.org_qty"
                    @change="onPrice"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="remove(scope)"
                    icon="el-icon-delete"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import {
  getStatementByCode,
  addCorrect,
  editCorrect,
  readCorrect
} from "@/api/changeAccount/changeAccount";
import { supplierList } from "@/api/supplier/supplierList";
import { getOrgData } from "@/api/middleorder/middleorderlist";
export default {
  props: {
    dialog: Object
  },
  data() {
    return {
      searchCode: "",
      settlementId: "",
      institutionList: [],
      formData1: {},
      formData: {
        amount: 0,
        num: 0,
        price: 0,
        qty: 0
      },
      rules: {},
      supplierData: {
        innerVisible: false,
        value: "",
        id: "",
        list: [],
        loading: false
      },
      institutionData: {
        innerVisible: false,
        value: "",
        list: [],
        loading: false
      }
    };
  },
  created() {},
  methods: {
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/api/correct/downloadTemplte?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //导入商品
    handleAvatarSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)"
      });
      let data = new window.FormData();
      data.append("upfile", param.file);
      data.append("token", getToken());
      this.$axios.post("/api/correct/importOrg", data).then(res => {
        loading.close();
        if (res.data.code == 0) {
          res.data.data.list.forEach(res => {});
          this.institutionList = res.data.data.list;
        } else {
          this.$message({
            type: "info",
            message: res.data.msg
          });
        }
      });
    },
    //修改金额和数量
    onPrice() {
      this.formData.price =
        (this.formData.amount / this.formData.num).toFixed(4) == Infinity
          ? 0
          : (this.formData.amount / this.formData.num).toFixed(4);
      if (
        this.formData.amount.toFixed(4) == 0.0 &&
        this.formData.num.toFixed(4) == 0.0
      ) {
        this.institutionList = [];
      }
    },
    // 搜索
    search() {
      let data = {
        code: this.searchCode
      };
      getStatementByCode(data).then(res => {
        this.formData1 = res.data.statement;
        this.settlementId = res.data.statement.id;
      });
    },
    //获取供应商Id
    supplierOn(id) {
      this.supplierData.id = id;
      console.log(this.supplierData);
    },
    // 嵌套搜索供应商数据
    supplierMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.supplierData.list = [];
      }
    },

    //获取供应商数据
    getSupplierList(query = "") {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      this.supplierData.loading = true;
      supplierList(data).then(res => {
        this.supplierData.list = res.data.data.map(item => {
          return {
            value: `${item.id}`,
            label: `[${item.code}]${item.name}`
          };
        });
        this.supplierData.loading = false;
      });
    },
    // 嵌套搜索机构数据
    institutionMethod(query) {
      if (query !== "") {
        this.getinstitutionList(query);
      } else {
        this.institutionData.list = [];
      }
    },

    //获取机构数据
    getinstitutionList(query = "") {
      let data = {
        key: query,
        page: 1,
        limit: 100
      };
      this.institutionData.loading = true;
      getOrgData(data).then(res => {
        this.institutionData.list = res.data.map(item => {
          return {
            value: `${item.erp_org_code}`,
            label: `[${item.erp_org_code}]${item.name}`,
            org_id: `${item.id}`
          };
        });
        this.institutionData.loading = false;
      });
    },
    // 添加机构
    addInstitution() {
      let boolArr = this.institutionList.filter(res => {
        return res.org_code == this.institutionData.value;
      });
      if (boolArr.length == 0) {
        let filterArr = this.institutionData.list.filter(res => {
          return res.value == this.institutionData.value;
        });
        this.institutionList.push({
          org_name: filterArr[0].label,
          org_code: filterArr[0].value,
          org_id: filterArr[0].org_id,
          org_amount: 0,
          org_num: 0,
          org_qty: 0
        });
      } else {
        this.$message({
          type: "info",
          message: "该机构已添加"
        });
      }
    },
    //删除机构
    remove(scope) {
      this.institutionList.forEach((res, index) => {
        if (res.org_id == scope.row.org_id) {
          this.institutionList.splice(index, 1);
        }
      });
    },
    getData() {
      this.getSupplierList();
      this.getinstitutionList();
      if (this.dialog.dialogType == "edit") {
        let data = {
          id: this.dialog.id
        };
        readCorrect(data).then(res => {
          this.formData1 = res.data.correct.statement;
          this.searchCode = res.data.correct.statement.serial_code;
          this.settlementId = res.data.correct.statement.id;
          this.formData = {
            amount: res.data.correct.amount,
            num: res.data.correct.num,
            price: res.data.correct.price,
            qty: res.data.correct.qty
          };
          this.supplierData.value = res.data.correct.supplier_name;
          this.supplierData.id = res.data.correct.supplier_id;
          this.institutionList = Object.values(res.data.correct.orglist);
        });
      }
    },
    hideDialog() {
      this.institutionList = [];
      this.searchCode = "";
      this.settlementId = "";
      this.formData1 = {};
      this.formData = {
        amount: 0,
        num: 0,
        price: 0,
        qty: 0
      };
      this.supplierData = {
        innerVisible: false,
        value: "",
        list: [],
        loading: false
      };
      this.institutionData = {
        innerVisible: false,
        value: "",
        list: [],
        loading: false
      };
      this.dialog.dialogVisible = false;
    },
    //提交
    confirm() {
      if (this.searchCode) {
        let orglist = {};
        this.institutionList.forEach(res => {
          orglist[res.org_id] = {
            org_id: res.org_id,
            org_amount: res.org_amount,
            org_num: res.org_num,
            org_qty: res.org_qty
          };
        });
        let data = {
          statement_id: this.settlementId,
          supplier_id: this.supplierData.id,
          amount: this.formData.amount,
          num: this.formData.num,
          qty: this.formData.qty,
          orglist: JSON.stringify(orglist)
        };
        console.log(data, 99999);
        if (this.dialog.dialogType == "edit") {
          data.id = this.dialog.id;
          editCorrect(data)
            .then(res => {
              if (res.code == 0) {
                this.$message({
                  message: res.message || res.msg,
                  type: "success"
                });
                this.hideDialog();
                this.$emit("upData");
              } else {
                this.$message({
                  message: res.message || res.msg,
                  type: "error"
                });
              }
            })
            .catch(res => {
              console.log(res);
            });
        } else {
          addCorrect(data)
            .then(res => {
              if (res.code == 0) {
                this.$message({
                  message: res.message || res.msg,
                  type: "success"
                });
                this.hideDialog();
                this.$emit("upData");
              } else {
                this.$message({
                  message: res.message || res.msg,
                  type: "error"
                });
              }
            })
            .catch(res => {
              console.log(res);
            });
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择原账单"
        });
      }
    },
    //取消
    cancel() {
      this.hideDialog();
    }
  }
};
</script>
<style scoped>
.main {
  display: flex;
  justify-content: space-around;
}
.main .inp {
  width: 400px;
}
.main .inps {
  padding: 0;
  border-radius: 4px;
  color: #606266;
  display: inline-block;
  height: 37px;
  line-height: 37px;
  padding: 0 15px;

  width: 400px;
  margin: 0;
}
.main .left {
  width: 45%;
}
.main .right {
  width: 45%;
}
.main .title {
  font-size: 14px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}
.search {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  height: 45px;
}
.search .searchName {
  width: 100px;
  font-size: 14px;
  color: #606266;
  font-weight: 700;
}
.search .searchInp {
  width: 250px;
  margin-right: 10px;
}
.el-form-item__content {
  height: 40px !important;
  overflow: hidden;
}
.el-form-item {
  margin-bottom: 15px !important;
  height: 40px !important;
  overflow: hidden;
}
.institution {
  width: 700px;
}
</style>
